package com.study.d2_reflect;

import org.junit.Test;

import java.lang.reflect.Constructor;

public class Test2Constructor {
    @Test
    public void testGetConstructors() {
        //反射第一步：先拿到这个类的Class对象
        Class c = Student.class;

        //获取类的全部构造器
        //只能拿public的
//              Constructor[] constructors = c.getConstructors();
        //存在即可拿
        Constructor[] declaredConstructors = c.getDeclaredConstructors();
        //遍历构造器
        for (Constructor declaredConstructor : declaredConstructors) {
            System.out.println(declaredConstructor.getName() + "==>" + declaredConstructor.getParameterCount());
        }
    }
    @Test
    public void testGetConstructor() throws Exception{
        Class<Student> studentClass = Student.class;
        //无参
        Constructor<Student> c1 = studentClass.getDeclaredConstructor();
        //四个参
        Constructor<Student> c2 = studentClass.getDeclaredConstructor(String.class, int.class, char.class, double.class);

        //得到的构造器的目的依然是初始化对象返回

        //如果构造器是private的可以用c1.setAccessible（true）禁止访问权限检查
        Student student = c1.newInstance();
        System.out.println(student);
        Student student1 = c2.newInstance("嘿嘿",15,'男',175.8);
        System.out.println(student1);
    }
}
